<?php
include("includes/country.php");
$country=new  Country();

//page;
$title	= CheckOut;
$name	= CheckOut;

//get info user if logined:
$idAccount 			= CheckLogin();
$HostingOption		= gpc_getSession("HostingOption");
$DomainOption		= gpc_getSession("DomainOption");


if(!is_array($HostingOption) || !is_array($DomainOption))
{
	Redirect($folder_path_root."signup/");
}

if($idAccount>0)
{
	$accountinfo	= getInfoAccount($idAccount);
}
///======================================================
$step				= 3;
$datereg			= gpc_getDateNow();
$daterrr			= gpc_add_date($datereg,2);
$FirstName			= gpc_getStringPost('FirstName',$accountinfo['cFirstName']);
$LastName			= gpc_getStringPost('LastName',$accountinfo['cLastName']);
$fullname			= $FirstName.' '.$LastName;
$PrimaryEmail		= gpc_getStringPost('PrimaryEmail',$accountinfo['cEmail']);
$SecondaryEmail		= gpc_getStringPost('SecondaryEmail',$accountinfo['cEmail2']);
$CompanyName		= gpc_getStringPost('CompanyName',$accountinfo['cCompany']);
$Address1			= gpc_getStringPost('Address1',$accountinfo['cAddress']);
$Address2			= gpc_getStringPost('Address2',$accountinfo['cAddress2']);
$Address3			= gpc_getStringPost('Address3',$accountinfo['cAddress3']);
$Town				= gpc_getStringPost('Town',$accountinfo['cCity']);
$County				= gpc_getStringPost('County',$accountinfo['cState']);
$PostCode			= gpc_getStringPost('PostCode',$accountinfo['cZipCode']);
$CountryCode		= gpc_getStringPost('CountryCode',$accountinfo['cCountry']);
$HomePhone			= gpc_getStringPost('HomePhone',$accountinfo['cHomePhone']);
$WorkPhone			= gpc_getStringPost('WorkPhone',$accountinfo['cWorkPhone']);
$MobilePhone		= gpc_getStringPost('MobilePhone',$accountinfo['cMobiPhone']);
$FaxNumber			= gpc_getStringPost('FaxNumber',$accountinfo['cFax']);
$PaymentMethod		= gpc_getStringPost('PaymentMethod');

$isPost				= gpc_getBoolPost('ActionPost');
$hostingName		= 'N/A';

//save paymentmethod
gpc_setSession("PaymentMethod",$PaymentMethod);

if(!empty($FirstName) && !empty($LastName) && !empty($PrimaryEmail) && !empty($Address1) && $isPost)
{
	$totalPrice		= 0; //TOTAL PRICE
	$accountLogin	=''; //USE TO SEND EMAIL
	$orderdetail	=''; //ODERDETAIL USE SAVE TO ORDER AND SEND EMAIL
	$domainReg		= array();//DOMAINS WILL REG
	$domain_traf	= '';//DOMAINS TRANSFER
	$order_name		= '';

	if($HostingOption==null && $DomainOption==null)
	{
		$msg_return=YourNotChoisePackageYet;
		$msg_return.=' <input type="button" value="'.Back.'" onclick="location=\'/signup/\'">';
	}
	else if(CheckEmail($PrimaryEmail) && $idAccount==false)//check email exists?
	{
		$msg_return=EmailisExistsPleaselogin;

	}else
	{
		$customerinfo = (!empty($CompanyName))? '<b>'.Company.':</b> '.$CompanyName.'<br>' : '';
		$customerinfo.= '<b>'.FullName.':</b> '.$fullname.'<br>';
		$customerinfo.= '<b>'.Address.':</b> '.$Address1.'<br>';
		$customerinfo.= (!empty($Town))? '<b>'.City.':</b> '.$Town.'<br>':'';
		$customerinfo.= (!empty($CountryCode))? '<b>'.Country.':</b> '.$country->getNameByCode($CountryCode).'<br>':'';

		//CHECK ACCOUNT
		if($idAccount==false)
		{
			//ADD USER IF NOT EXIST
			$password	= gpc_randPass();
			$accountLogin = '<br><br><b>'.AccountForLogin.':</b> <br>';
			$accountLogin.= '<b>'.Email.':</b> '.$PrimaryEmail.'<br>';
			$accountLogin.= '<b>'.Password.':</b> '.$password.'<br>';

			$idAccount=InsertAccount($FirstName,$LastName,$username,$password,$PrimaryEmail,$SecondaryEmail,$CompanyName,$Address1,$Address2,$Address3,
			$Town,$County,$PostCode,$CountryCode,$HomePhone,$WorkPhone,$MobilePhone,$FaxNumber,"",-2,1);
		}else {
			//UPDATE USER INFO IF EXIST
			UpdateAccount($idAccount,$FirstName,$LastName,"","",$SecondaryEmail,$CompanyName,$Address1,$Address2,$Address3,
			$Town,$County,$PostCode,$CountryCode,$HomePhone,$WorkPhone,$MobilePhone,$FaxNumber);
		}

		if($idAccount>0)
		{
			//check hosting:
			if(is_array($HostingOption) && count($HostingOption)==2)
			{
				// $HostingOption FORMAT ARRAY(TYPE,ID) E.G "Y|3"
				//has hosting
				$hostingRank	= $HostingOption[1];//year
				$idHosting		= $HostingOption[0];//id

				$hostingInfo	= getInfoHosting($idHosting);
				if($hostingRank=="y")
				{
					$hostingInfo['price']	= $hostingInfo['iPrice1Year'];
					$strhostingrank	= "1 ".Year;
					$hostingInfo['monthuse']=12;
				}else {
					$hostingInfo['price']	= $hostingInfo['iPrice6Mon'];
					$strhostingrank	= "6 ".Month;
					$hostingInfo['monthuse']=6;
				}
				$totalPrice+=$hostingInfo['price'];
			}

			//check domain:
			$domainReg=array();
			foreach ($DomainOption as $i =>$info)
			{
				$info['price']=getPriceDomain($info['name'])*intval($info['year']);
				if($info['year']=="tranfer")
				{
					$domain_traf.=$info['name'].",";
					continue;
				}

				$totalPrice+=$info['price'];
				$domainReg[]=$info;
			}

			$PriceVAT =$totalPrice*10/100;
			//---------------------------------------

			//insert order:
			$idOrder=InsertOrder($idAccount,$orderdetail,$datereg);

			if($idOrder>0)
			{
				gpc_setSession("IdOrder",$idOrder);
				//insert order service hosting
				$orderdetail='<table width="100%" style="background:#dddddd" cellpadding="2" cellspacing="1">
						<tr bgcolor="#EFEFEF">
							<th align="center">'.ServiceCode.'</th>
							<th align="center">'.InforDetailOrder.'</th>
							<th align="center">'.Payment.'</th>
						</tr>';

				if(isset($hostingInfo))
				{
					$idsv=InsertService($idAccount,$idOrder,$hostingInfo['cName'],"hosting",$hostingInfo['iId'],$hostingInfo['monthuse'],'',$datereg);
					$order_name .=$hostingInfo['cName'].',';
					$orderdetail.='
						<tr bgcolor="#fefefe">
							<td align="center">'.getServiceCode($idsv).'</td>
							<td>Hosting Plan: <b>'.$hostingInfo['cName'].'</b> in '.$strhostingrank.'</td>
							<td align="right">'.getPriceClient($hostingInfo['price']).'</td>
						</tr>';
				}

				//insert order service domain
				foreach ($domainReg as $i=>$domain)
				{
					$idsv=InsertService($idAccount,$idOrder,$domain['name'],"domain",0,$domain['year']*12,'',$datereg);
					$order_name .=$domain['name'].',';
					$orderdetail.='<tr bgcolor="#fefefe">
								<td align="center">'.getServiceCode($idsv).'</td>
								<td>'.DomainName.': <b>'.$domain['name'].'</b> in '.$domain['year'].' '.Year.'</td>
								<td align=right>'.getPriceClient($domain['price']).'</td>
							</tr>';
				}

				/*$orderdetail.='
					<tr bgcolor="#fefefe">
						<td colspan=2 align="right"><b>'.MoneyneedPayment.':</b></td>
						<td align="right">'.getPriceClient($totalPrice).'</td>
					</tr>';
				*/
				/*
					<tr bgcolor="#fefefe">
						<td colspan=2 align="right"><b>'.TVAT.':</b></td>
						<td align="right">'.getPriceClient($PriceVAT).'</td>
					</tr>
				*/
				$orderdetail.='
					<tr bgcolor="#fefefe">
						<td colspan=2 rowspan=2 align="right" valign="middle"><b>'.TotalPrice.':</b></td>
						<td align="right">'.getPriceClient($totalPrice).'</td>
					</tr>
					<tr bgcolor="#fefefe">
						<td align="right">'.getPriceClient($totalPrice,false,false).'</td>
					</tr>
				</table>';
				$orderdetail.=NoteNotVAT.'<br>';

				if(!empty($domain_traf))$orderdetail.='<br>'.DomainTransfer.': '.$domain_traf.'<br>';

				UpdateOrder($idOrder,$order_name,$orderdetail);


				//send email to cus and admin:
				$str_paymentmethod	= getPaymentMethod($PaymentMethod);
				$strDateReg	= '<div>'.DATEMORDER.': '.gpc_DisplayDate($datereg).'</div><div>'.DATEENDPAY.': '.gpc_DisplayDate($daterrr).'</div>';
				$orderdetail= $strDateReg.$orderdetail;

				$emailconfig	= LoadConfigObj("ConfirmOrderEmail");

				$email_title= empty($emailconfig['title'])? TitleEmailOrder: $emailconfig['title'];
				$email_title= preg_replace("(({)(.*)(}))"," #".getOrderCode($idOrder)." ",$email_title);

				$email_msg	= $emailconfig['content'];
				$email_msg	= str_replace("{CUSTOMERINFO}",$customerinfo,$email_msg);
				$email_msg	= str_replace("{ACCOUNTLOGININFO}",$accountLogin,$email_msg);
				$email_msg	= str_replace("{ORDERCODE}",getOrderCode($idOrder),$email_msg);
				$email_msg	= str_replace("{ORDERDETAIL}",$orderdetail,$email_msg);
				$email_msg	= str_replace("{PAYMENTMETHOD}",$str_paymentmethod,$email_msg);

				send_email($PrimaryEmail,$fullname,$email_title,$email_msg,array($email_hosting),$email_hosting,$email_hosting_name);

				//delete options selected:
				gpc_removeSession("HostingOption");
				gpc_removeSession("DomainOption");


				//redirect to page success and exit
				Redirect($folder_path_root."checkout/success/".$idOrder."/");

			}else
			{
				$msg_return=ErrorPleasetryagain;
			}

		}else
		{
			$msg_return=ErrorPleasetryagain;
		}
	}
}else
{
}

?>